const svc = require('../util/service'),
    logger = require('log4js').getLogger()

module.exports = (req, res) => {
    svc.handlePost(req, res, (reqObj, resolve) => {
        if (!reqObj.phone) {
            resolve({
                result: -1,
                msg: '缺少phone'
            })
            return
        }
        const mongoMng = require('../mng/mongoMng')
        if (!mongoMng.db) {
            logger.error('[' + __filename + ':' + __line + ']', '未连接mongo')
            resolve({
                result: -1,
                msg: '系统错误'
            })
            return
        }
        new Promise(resolve => {
            var $set = {}
            var promises = []
            if (reqObj.name) {
                $set.name = reqObj.name
            }
            if (reqObj.isPromoter) {
                promises.push(new Promise(resolve => {
                    genWechatQrcode(reqObj.phone).then(result => {
                        logger.debug('[' + __filename + ':' + __line + ']', JSON.stringify(result))
                        $set.wechatSceneId = result.wechatSceneId
                        $set.wechatQrcode = result.wechatQrcode
                        $set.isPromoter = true
                        resolve()
                    }, result => {
                        logger.error('[' + __filename + ':' + __line + ']', result || '')
                        resolve()
                    })
                }))
            }
            if (promises.length == 0) {
                resolve($set)
            } else {
                Promise.all(promises).then(result => {
                    resolve($set)
                })
            }
        }).then($set => {
            mongoMng.db.collection('user').update({
                phone: reqObj.phone
            }, {
                $set
            }, (err, result) => {
                if (err) {
                    logger.error('[' + __filename + ':' + __line + ']', err)
                    resolve({
                        result: -1,
                        msg: '系统错误'
                    })
                    return
                }
                resolve({
                    result: 1
                })
            })
        })
    })
}

function genWechatQrcode(phone) {
    const mongoMng = require('../mng/mongoMng')
    return new Promise((resolve, reject) => {
        mongoMng.db.collection('user').find({
            phone
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject()
                return
            }
            if (result.length == 0) {
                logger.error('[' + __filename + ':' + __line + ']', 'no phone', phone)
                reject()
                return
            }
            if (result[0].wechatQrcode && result[0].wechatSceneId) {
                resolve({
                    wechatQrcode: result[0].wechatQrcode,
                    wechatSceneId: result[0].wechatSceneId
                })
                return
            }
            findWechatSceneId().then(wechatSceneId => {
                require('../mng/wechatMng').client('etourly').qrcodeCreate({
                    scene_id: wechatSceneId
                }).then(result => {
                    resolve({
                        wechatSceneId,
                        wechatQrcode: 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' + result.ticket
                    })
                }, result => {
                    logger.error('[' + __filename + ':' + __line + ']', result || '')
                    reject()
                })
            }, result => {
                logger.error('[' + __filename + ':' + __line + ']', result || '')
                reject()
            })
        })
    })
}

function findWechatSceneId(times) {
    var times = times || 0
    if (times > 10)
        return Promise.reject()
    const mongoMng = require('../mng/mongoMng')
    return new Promise((resolve, reject) => {
        let idx = require('../../lib/random')(1, 100000)
        mongoMng.db.collection('user').find({
            wechatSceneId: idx
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject()
                return
            }
            if (result.length > 0) {
                findWechatSceneId(times + 1).then(result => {
                    resolve(result)
                }, reuslt => {
                    reject(result)
                })
                return
            }
            resolve(idx)
        })
    })
}